package interfaz2;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Label;

import core.Post;
import events.PostStateChangedEvent;
import events.PostStateChangedListener;

/**
 * Following the MVC design pattern this class is the view of a Post.
 * 
 * @author ole
 */
public class PostView extends DustComposite {
	// Class constants.
	private final int N_ELEMS = 3;
	private final String RSS_STR = "State: RSS";
	private final String SAVED_STR = "State: Saved";
	
	// Class attributes.
	private Post post;
	private Label state_label;
	
	/*
	 * Private classes
	 */
	
	/**
	 * This class will handle when a Post change its state so we can change
	 * the state in the view.
	 * 
	 * @author ole
	 */
	private class ChangeState implements PostStateChangedListener, Runnable {
		private PostStateChangedEvent event;

		@Override
		public void handleEvent(PostStateChangedEvent event) {
			this.event = event;
			if (!PostView.this.isDisposed())
				getDisplay().asyncExec(this);
		}

		@Override
		public void run() {
			String state_str;
			
			if (event.getActualState() == Post.Post_state.ACTUAL)
				state_str = RSS_STR;
			else
				state_str = SAVED_STR;
			
			state_label.setText(state_str);
			layout();
		}
	}
	
	/*
	 * Public methods of class PostView
	 */
	
	/**
	 * Class constructor.
	 * 
	 * @param comp:
	 * 		The parent composite of this Composite.
	 * @param post:
	 * 		The post that this view will represent.
	 * @param browser:
	 * 		The browser where the post will be shown.
	 */
	public PostView(DustComposite comp, Post post, Browser browser) {
		super(comp, SWT.NONE);
		
		Label label;
		GridData grid;
		String state_msg;
		
		this.setLayout(new GridLayout(N_ELEMS, false));
		
		// The Post we are maintaining. Add a handler to change the state label
		// when necessary.
		this.post = post;
		this.post.addPostStateChangedListener(new ChangeState());
		
		// The top Composite will have the author of this post.
		label = new Label(this, SWT.NONE);
		label.setText("Author: " + post.getAuthor());
		grid = new GridData(SWT.FILL, SWT.FILL, false, false);
		label.setLayoutData(grid);
		
		// The top Composite will have the type of update of this post.
		label = new Label(this, SWT.NONE);
		label.setText("Via: " + post.getUpdateType().toString());
		grid = new GridData(SWT.FILL, SWT.FILL, false, false);
		label.setLayoutData(grid);
		
		// The top Composite will have the state of this post.
		state_label = new Label(this, SWT.NONE);
		state_msg = post.isActual()? RSS_STR: SAVED_STR;
		state_label.setText(state_msg);
		grid = new GridData(SWT.FILL, SWT.FILL, false, false);
		state_label.setLayoutData(grid);
		
		comp.layout();
	}
	
	/**
	 * Returns the Post associated to this view.
	 * 
	 * @return:
	 * 		The Post associated to this view.
	 */
	public Post getPost() {
		return post;
	}
}
